package internal.internal;

import internal.sitemesh.Sitemesh;

import java.util.regex.Matcher;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletResponse;

import org.lightcommons.util.PatternMap.MatchedResult;
import org.lightmtv.config.BeanFactory;
import org.lightmtv.config.GlobalContext;
import org.lightmtv.config.MtvFilter;
import org.lightmtv.config.MtvFilterChain;
import org.lightmtv.config.UrlConfigEntry;
import org.lightmtv.request.Request;
import org.lightmtv.response.Response;

public class InternalMtvFilter implements MtvFilter{

	private FilterChain servletChain;
	private HttpServletResponse servletResponse;
	
	public Response doFilter(Request request, MtvFilterChain chain) {
		MatchedResult<UrlConfigEntry> matchedResult = GlobalContext.getSettings().getUrlPatternMap().matcher(request.getPath());
		Response response = null;
		if(matchedResult!=null){
			UrlConfigEntry entry = matchedResult.getResult();
			Matcher matcher = matchedResult.getMatcher();
			String path = buildPath(matcher, entry.getPath());
			switch (entry.getType()) {
			case UrlConfigEntry.ACTION:
				BeanFactory beanFactory = GlobalContext.getSettings().getBeanFactory();
				response = new ActionHandler(beanFactory,path).getHttpResult(request);
				break;
			case UrlConfigEntry.INCLUDE:
				response = new IncludeHandler(path).getHttpResult(request);
				break;
			case UrlConfigEntry.REDIRECT:
				response = new RedirectHandler(path).getHttpResult(request);
				break;
			case UrlConfigEntry.REWRITE:
				response = new RewriteHandler(path).getHttpResult(request);
				break;
			default:
				break;
			}
		}
		if(response == null && servletChain != null){
			try{
				Sitemesh sitemesh = new Sitemesh(request.getServletRequest(),servletResponse);
				sitemesh.activeSitemesh("UTF-8");
				sitemesh.chain(servletChain);
				sitemesh.getResponseWrapper();
				//TODO:
			}catch(Throwable t){
				//handle internal error
			}
		}
		return response;
	}

	private String buildPath(Matcher matcher,String path){
		for(int i=0;i<=matcher.groupCount();i++){
			path=path.replaceAll("\\$"+i, matcher.group(i));
		}
		return path;
	}
	
}
